package com.example.techstudy.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.example.techstudy.entity.Student;
import com.example.techstudy.mapper.StudentMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author: Administrator
 * @date: 2021/3/9 0:20
 */
@Service
public class StudentService {

    @Resource
    private StudentMapper studentMapper;

    @Resource
    private TransactionTemplate transactionTemplate;

    public void create(Student student) {
        System.out.println(111);
        // studentMapper.insert(student);
    }

    public void test1() {
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Student::getAge, 1)
                .eq(Student::getId, 2)
                .and(i -> i.eq(Student::getName, "zhangsan")
                        .or(j -> j.eq(Student::getName, "lisi").between(Student::getAge, 15, 20)));
        List<Student> students = studentMapper.selectList(wrapper);
    }

    public void testTrans() {
        transactionTemplate.execute(s -> {
            try {
                update2();
                update1();
                if (true) {
                    throw new RuntimeException("manual exception");
                }
                return true;
            } catch (Exception e) {
                s.setRollbackOnly();
                return false;
            }
        });
    }

    private void update1() {
        LambdaUpdateWrapper<Student> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Student::getId, 1)
                .set(Student::getAge, 3);
        studentMapper.update(null, updateWrapper);
    }

    private void update2() {
        LambdaUpdateWrapper<Student> updateWrapper1 = new LambdaUpdateWrapper<>();
        updateWrapper1.eq(Student::getId, 2)
                .set(Student::getAge, 4);
        studentMapper.update(null, updateWrapper1);

    }

    public void testNonTrans() {
        update1();
        update2();
        throw new RuntimeException("manual exception");
    }
}
